package qj.tool.volatileidexim;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

import qj.tool.volatileidexim.VolatileIdEximConfig;
import qj.tool.volatileidexim.VolatileIdEximConfig.ConfigType;
import qj.tool.volatileidexim.VolatileIdEximConfig.TestType;
import qj.util.ZipUtil;
import qj.util.ZipUtil.ZipWriter;
import qj.util.funct.F1;
import qj.util.funct.P1;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

@SuppressWarnings("unchecked")
public class DataExporter {

	private VolatileIdEximConfig config;

	public DataExporter(VolatileIdEximConfig config) {
		this.config = config;
	}
	
	public void export(OutputStream zipOut) {
		final Charset charset = Charset.forName("UTF-8");
		ZipWriter zipWriter = ZipUtil.zipWriter(zipOut);
		final Gson gson = config.gsonBuilder.create();
		
		for (final ConfigType type : config.types.values()) {
			zipWriter.writeEntry(type.clazz.getSimpleName() + ".json", new P1<OutputStream>() {public void e(final OutputStream out) {
				type.loadF.e(new P1<Object>() {public void e(Object obj) {
					try {
						out.write(gson.toJson(obj).getBytes(charset));
						out.write("\n<END>\n".getBytes());
					} catch (IOException e1) {
						throw new RuntimeException(e1.getMessage(), e1);
					}
				}});
			}});
		}
		zipWriter.finish();
	}
	
	public static void main(String[] args) {
		TestType o = new TestType();
		o.id = "123";
		System.out.println(new Gson().toJson(o));
//		System.out.println(new Gson().fromJson("[{\"id\":\"123\"}]", new TypeToken<Collection<TestType>>(){}.getType()));
		
	}
	
	
}
